//! Implementation of the Picture Manager class
/*!
\file PictureManager.cpp
\author Thomas Pfeiffer
\date 13.11.2012
*/

#include <string>
#include <algorithm>
#include <functional>
#include "PictureManager.h"

/*!
Functor to check if two pictures have the same name
with an stl algorithm
*/
class DuplicatePictureFunctor {
public:
  //! Constructor of the Functor.
  /*!
  Constructor of the Functor. Takes one Argument because it stores information
  \param s The Name of the picture you want to compare to the others.
  */
	DuplicatePictureFunctor(std::string const& s) : mName(s) {}

  //! Override the () operator to make an object of this class act like a function
  /*!
  Compares the stored mName to the name of the picture p
  \param p The picture whose name is compared to the stored name.
  */
	bool operator()(Picture * p) {
		return p->getFileName() == mName;
	}

private:
	std::string mName;
};

PictureManager::~PictureManager()
{
	// free all pictures in the list
	std::for_each(mPictures.begin(), mPictures.end(), deleteObject);
}

void PictureManager::SavePictures() const
{
	// call write on every picture in the list
	for (TPicturesConstIterator it = mPictures.begin(); it != mPictures.end(); ++it) {
		(*it)->WriteSVG();
	}
}

Picture* PictureManager::getPicture( std::string const& name ) const
{
	DuplicatePictureFunctor dpf(name);
	TPicturesConstIterator it = find_if(mPictures.begin(), mPictures.end(), dpf);
	if (it == mPictures.end())
		return 0;  // return 0 if picture wasn't found

	return *it;  // return pointer to picture if found
}

void PictureManager::addPicture( Picture * pic )
{
	DuplicatePictureFunctor dpf(pic->getFileName());

	TPicturesIterator it = find_if(mPictures.begin(), mPictures.end(), dpf);
	if (it == mPictures.end()) {
		mPictures.push_back(pic);
	}
}